﻿'
' DotNetNuke® - http://www.dotnetnuke.com
' Copyright (c) 2002-2009
' by DotNetNuke Corporation
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
' DEALINGS IN THE SOFTWARE.
'


Imports DotNetNuke
Imports DotNetNuke.Entities.Modules
Imports System.Globalization
Imports System.Web.UI.WebControls

Namespace DotNetNuke.Modules.Announcements

    ''' <summary>
    ''' The EditAnnouncements PortalModuleBase is used to manage Announcements
    ''' </summary>
    ''' <remarks>
    ''' </remarks>
    ''' <history>
    ''' 	[cnurse]	9/20/2004	Moved Announcements to a separate Project
    ''' 	[cnurse]	9/20/2004	Updated to reflect design changes for Help, 508 support
    '''                       and localisation
    ''' 	[erikvb]	11/20/2007	updated for version 4.0.0 of the module
    '''     [erikvb]    10/20/2008  updated for version 4.0.2 of the module
    ''' </history>
    Partial Class EditAnnouncements

        Inherits Entities.Modules.PortalModuleBase

#Region " Private Members"

        Private itemId As Integer
        Private is24HourClock As Boolean = String.IsNullOrEmpty(CultureInfo.CurrentCulture.DateTimeFormat.AMDesignator)

#End Region

#Region " Event Handlers"

        ''' <summary>
        ''' Page_Load runs when the control is loaded
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        ''' <remarks></remarks>
        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Try
                ' get itemid
                If Not (Request.QueryString("ItemId") Is Nothing) Then
                    itemId = Int32.Parse(Request.QueryString("ItemId"))
                Else
                    itemId = Convert.ToInt32(Common.Utilities.Null.NullInteger)
                End If
                cmdCalendar.NavigateUrl = DotNetNuke.Common.Utilities.Calendar.InvokePopupCal(txtPublishDate)
                cmdCalendar2.NavigateUrl = DotNetNuke.Common.Utilities.Calendar.InvokePopupCal(txtExpireDate)

                If (Settings.Contains("editorHeight")) AndAlso (Settings("editorHeight").ToString <> "") Then
                    Me.teDescription.Height = Integer.Parse(Settings("editorHeight").ToString)
                Else
                    Me.teDescription.Height = 300
                End If

                If Page.IsPostBack = False Then
                    urlImage.FileFilter = glbImageFileTypes
                    urlImage.ShowNone = True

                    ctlURL.ShowLog = True
                    ctlURL.ShowNewWindow = True
                    ctlURL.ShowTrack = True
                    ctlURL.ShowUsers = True

                    ' delete confirmation
                    DotNetNuke.UI.Utilities.ClientAPI.AddButtonConfirm(cmdDelete, Localization.GetString("DeleteItem"))


                    InitializeHours(ddlHoursPublish)
                    InitializeMinutes(ddlMinutesPublish)
                    InitializeAmPm(ddlAmPmPublish, phAmPmPublish)

                    InitializeHours(ddlHoursExpire)
                    InitializeMinutes(ddlMinutesExpire)
                    InitializeAmPm(ddlAmPmExpire, phAmPmExpire)

                    If Not Common.Utilities.Null.IsNull(itemId) Then

                        ' get object
                        Dim objAnnouncements As New AnnouncementsController
                        Dim objAnnouncement As Model.Announcement = objAnnouncements.GetAnnouncement(itemId, ModuleId)

                        If Not objAnnouncement Is Nothing Then
                            ' populate controls
                            txtTitle.Text = objAnnouncement.Title.ToString
                            urlImage.Url = objAnnouncement.ImageSource
                            teDescription.Text = objAnnouncement.Description
                            ctlURL.Url = objAnnouncement.Url
                            If Not Common.Utilities.Null.IsNull(objAnnouncement.ViewOrder) Then
                                txtViewOrder.Text = Convert.ToString(objAnnouncement.ViewOrder)
                            End If
                            SetDateTimeValue(objAnnouncement.PublishDate, txtPublishDate, ddlHoursPublish, ddlMinutesPublish, ddlAmPmPublish)
                            SetDateTimeValue(objAnnouncement.ExpireDate, txtExpireDate, ddlHoursExpire, ddlMinutesExpire, ddlAmPmExpire)

                            ctlAudit.CreatedDate = objAnnouncement.CreatedDate.ToString
                            ctlAudit.CreatedByUser = objAnnouncement.CreatedByUser.ToString

                            ctlTracking.URL = objAnnouncement.Url
                            ctlTracking.ModuleID = ModuleId

                        Else ' security violation attempt to access item not related to this Module
                            Response.Redirect(NavigateURL(), True)
                        End If
                    Else ' new item
                        txtPublishDate.Text = DateTime.Today.ToShortDateString
                        cmdDelete.Visible = False
                        ctlAudit.Visible = False
                        ctlTracking.Visible = False
                    End If

                End If
            Catch exc As Exception
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

        ''' <summary>
        ''' cmdCancel_Click runs when the cancel button is clicked
        ''' 
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        ''' <remarks></remarks>
        Private Sub cmdCancel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdCancel.Click
            Try
                Response.Redirect(NavigateURL(), True)
            Catch exc As Exception           'Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

        ''' <summary>
        ''' cmdDelete_Click runs when the delete button is clicked
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        ''' <remarks></remarks>
        Private Sub cmdDelete_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdDelete.Click
            Try
                If Not Common.Utilities.Null.IsNull(itemId) Then
                    ' delete item
                    Dim objAnnouncements As New AnnouncementsController
                    objAnnouncements.DeleteAnnouncement(ModuleId, itemId)
                    ' refresh cache
                    ModuleController.SynchronizeModule(ModuleId)
                End If

                ' redirect back to page
                Response.Redirect(NavigateURL(), True)
            Catch exc As Exception
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

        ''' <summary>
        ''' cmdUpdate_Click runs when the update button is clicked
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        ''' <remarks></remarks>
        Private Sub cmdUpdate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdUpdate.Click
            Try
                ' verify data
                If Page.IsValid = True Then

                    Dim objAnnouncement As New Model.Announcement()

                    ' populate object
                    objAnnouncement.ItemId = itemId
                    objAnnouncement.ModuleID = ModuleId
                    objAnnouncement.CreatedByUser = UserInfo.UserID
                    objAnnouncement.CreatedDate = Now
                    objAnnouncement.Title = txtTitle.Text
                    objAnnouncement.ImageSource = urlImage.Url
                    objAnnouncement.Description = teDescription.Text
                    objAnnouncement.Url = ctlURL.Url
                    objAnnouncement.PublishDate = GetDateTimeValue(txtPublishDate, ddlHoursPublish, ddlMinutesPublish, ddlAmPmPublish)
                    objAnnouncement.ExpireDate = GetDateTimeValue(txtExpireDate, ddlHoursExpire, ddlMinutesExpire, ddlAmPmExpire)

                    If txtViewOrder.Text <> "" Then
                        objAnnouncement.ViewOrder = Convert.ToInt32(txtViewOrder.Text)
                    End If

                    ' add or update
                    Dim objAnnouncements As New AnnouncementsController
                    If Common.Utilities.Null.IsNull(itemId) Then
                        objAnnouncements.AddAnnouncement(objAnnouncement)
                    Else
                        objAnnouncements.UpdateAnnouncement(objAnnouncement)
                    End If

                    ' refresh cache
                    ModuleController.SynchronizeModule(ModuleId)

                    ' url tracking
                    Dim objUrls As New UrlController
                    objUrls.UpdateUrl(PortalId, ctlURL.Url, ctlURL.UrlType, ctlURL.Log, ctlURL.Track, ModuleId, ctlURL.NewWindow)

                    ' redirect back to page
                    Response.Redirect(NavigateURL(), True)

                End If
            Catch exc As Exception
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

#End Region

#Region " DateTime field Methods"

        ''' <summary>
        ''' InitializeMinutes initializes the minutes dropdown
        ''' </summary>
        ''' <param name="MinutesDropDown"></param>
        ''' <remarks></remarks>
        Private Sub InitializeMinutes(ByVal MinutesDropDown As DropDownList)
            'setup minutes dropdown
            For i As Integer = 0 To 59
                MinutesDropDown.Items.Add(New ListItem(i.ToString("00"), i.ToString()))
            Next i
        End Sub
        ''' <summary>
        ''' InitializeHours initializes the hours dropdown based on whether the culture has 24 hour clock or 12 hour
        ''' </summary>
        ''' <param name="HoursDropDown"></param>
        ''' <remarks></remarks>
        Private Sub InitializeHours(ByVal HoursDropDown As DropDownList)
            Dim maxHour As Integer = 12
            Dim minHour As Integer = 1
            If is24HourClock Then
                minHour = 0
                maxHour = 23
            End If
            For i As Integer = minHour To maxHour
                If (i = 12) Then
                    If is24HourClock Then
                        HoursDropDown.Items.Add(New ListItem(i.ToString("00"), i.ToString()))
                    Else
                        HoursDropDown.Items.Insert(0, New ListItem(i.ToString("00"), i.ToString()))
                    End If
                Else
                    HoursDropDown.Items.Add(New ListItem(i.ToString("00"), i.ToString()))
                End If
            Next i
        End Sub
        ''' <summary>
        ''' if cullture has 12 hour clock InitializeAmPm initializes the am/pm dropdown
        ''' </summary>
        ''' <param name="AmPmDropDown"></param>
        ''' <param name="AmPmPlaceHolder"></param>
        ''' <remarks></remarks>
        Private Sub InitializeAmPm(ByVal AmPmDropDown As DropDownList, ByVal AmPmPlaceHolder As PlaceHolder)
            If Not is24HourClock Then
                'setup am/pm
                AmPmPlaceHolder.Visible = True
                AmPmDropDown.Items.Add(New ListItem(CultureInfo.CurrentCulture.DateTimeFormat.AMDesignator, "AM"))
                AmPmDropDown.Items.Add(New ListItem(CultureInfo.CurrentCulture.DateTimeFormat.PMDesignator, "PM"))
            Else
                AmPmPlaceHolder.Visible = False
            End If
        End Sub
        ''' <summary>
        ''' set values of datetime dropdowns and text field
        ''' </summary>
        ''' <param name="Value"></param>
        ''' <param name="DateText"></param>
        ''' <param name="HoursDropDown"></param>
        ''' <param name="MinutesDropDown"></param>
        ''' <param name="AmPmDropDown"></param>
        ''' <remarks></remarks>
        Private Sub SetDateTimeValue(ByVal Value As DateTime?, ByVal DateText As TextBox, ByVal HoursDropDown As DropDownList, ByVal MinutesDropDown As DropDownList, ByVal AmPmDropDown As DropDownList)
            If Value.HasValue Then
                DateText.Text = Value.Value.ToShortDateString()

                Dim hour As Integer = Value.Value.Hour
                Dim minute As Integer = Value.Value.Minute
                Dim isAM As Boolean = True

                If Not is24HourClock Then
                    If hour >= 12 Then
                        hour -= 12
                        isAM = False
                    End If
                    If hour = 0 Then
                        hour = 12
                    End If
                End If

                If HoursDropDown.Items.FindByValue(hour.ToString()) IsNot Nothing Then
                    HoursDropDown.Items.FindByValue(hour.ToString()).Selected = True
                End If

                If MinutesDropDown.Items.FindByValue(minute.ToString()) IsNot Nothing Then
                    MinutesDropDown.Items.FindByValue(minute.ToString()).Selected = True
                End If
                If Not is24HourClock Then
                    If isAM Then
                        AmPmDropDown.SelectedIndex = 0
                    Else
                        AmPmDropDown.SelectedIndex = 1
                    End If
                End If
            End If
        End Sub

        ''' <summary>
        ''' get values of date field and time dropdowns in one datetimxe value
        ''' </summary>
        ''' <param name="DateText"></param>
        ''' <param name="HoursDropDown"></param>
        ''' <param name="MinutesDropDown"></param>
        ''' <param name="AmPmDropDown"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Private Function GetDateTimeValue(ByVal DateText As TextBox, ByVal HoursDropDown As DropDownList, ByVal MinutesDropDown As DropDownList, ByVal AmPmDropDown As DropDownList) As DateTime
            Dim returnValue As DateTime = Null.NullDate
            If Not String.IsNullOrEmpty(DateText.Text) Then
                returnValue = DateTime.Parse(DateText.Text, CultureInfo.CurrentCulture)
                If HoursDropDown.SelectedValue <> "12" OrElse is24HourClock Then
                    returnValue = returnValue.AddHours(Int32.Parse(HoursDropDown.SelectedValue))
                End If
                returnValue = returnValue.AddMinutes(Int32.Parse(MinutesDropDown.SelectedValue))

                If Not is24HourClock AndAlso AmPmDropDown.SelectedValue.Equals("PM") Then
                    returnValue = returnValue.AddHours(12)
                End If
            End If
            Return returnValue
        End Function
#End Region

    End Class

End Namespace